from django.core.management.base import BaseCommand, CommandError
from django import apps
from django.db import transaction
from urllib.parse import urlparse, parse_qs
from apps.product.models import GoodsBlock, GoodsBlockChain
from apps.repo.models import StoreUnit, Repo
import datetime
from common import int_2_2d


unique_code_urls = """
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA00
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA01
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA02
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA03
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA04
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA05
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA06
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA07
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA08
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA09
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA10
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA11
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA12
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA13
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA14
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA15
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA16
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA17
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA18
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA19
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA20
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA21
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA22
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA23
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA24
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA25
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA26
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA27
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA28
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA29
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA30
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA31
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA32
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA33
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA34
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA35
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA36
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA37
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA38
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA39
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA40
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA41
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA42
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA43
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA44
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA45
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA46
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA47
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA48
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA49
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA50
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA51
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA52
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA53
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA54
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA55
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA56
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA57
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA58
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA59
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA60
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA61
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA62
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA63
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA64
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA65
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA66
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA67
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA68
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA69
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA70
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA71
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA72
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA73
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA74
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA75
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA76
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA77
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA78
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA79
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA80
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA81
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA82
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA83
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA84
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA85
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA86
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA87
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA88
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA89
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA90
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA91
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA92
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA93
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA94
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA95
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA96
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA97
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA98
https://api.zhegezhao.com/pages/blockChainInfo.html?unique_code=T0WR10DW32016C1AA99
"""

class Command(BaseCommand):
    help = ""

    def handle(self, *args, **options):
        split_rs = unique_code_urls.splitlines()
        for i, ucu in enumerate(split_rs):
            ucu = ucu.strip()
            if not ucu: continue
            print(i, ucu)
            rs = urlparse(ucu)
            params = parse_qs(rs.query, True)
            unique_code_param = params.get('unique_code', None)
            unique_code = unique_code_param[0] if unique_code_param else ''
            uc_parse_rs = GoodsBlock.parse_unique_code(unique_code)
            gb_data = uc_parse_rs

            product = gb_data['product']

            if GoodsBlock.objects.filter(unique_code=gb_data['unique_code']).first():
                continue
            if GoodsBlock.objects.filter(product=product).count() == product.publish_count:
                raise Exception('入库已完成（发行数量和入库数量已经一致）')
            with transaction.atomic():
                # 处理存储单元
                # 先找已存在的空闲
                su = StoreUnit.objects.filter(in_use=False).order_by('add_timestamp').first()
                if not su:
                    last_su = StoreUnit.objects.filter().order_by('add_timestamp').last()
                    if last_su:
                        last_su_int_fields = StoreUnit.str_fields_to_int(last_su.repo_no[2:])
                    else:
                        last_su_int_fields = None
                    # 生成新的
                    next_su_int_fields = StoreUnit.get_next_int_fields(last_su_int_fields)
                    if next_su_int_fields is None:
                        raise Exception('仓库无空闲存储空间')
                    repo = Repo.objects.filter().first()
                    next_su_fields = []
                    for i in range(len(next_su_int_fields)):
                        if i in [0, 6]:
                            next_su_fields.append(str(next_su_int_fields[i]))
                        elif i in [1, 3]:
                            next_su_fields.append(chr(next_su_int_fields[i]))
                        else:
                            next_su_fields.append(int_2_2d(next_su_int_fields[i]))
                    su = StoreUnit.objects.create(
                        repo=repo,
                        parent_type=StoreUnit.ParentType.CROWD_BOX_V1.name,
                        no=next_su_fields[-1],
                        fields=next_su_fields,
                        repo_no=repo.no + ''.join(next_su_fields),
                        in_use=False,
                    )

                gb_data.update({
                    "repo_id": su.repo.pk,
                    "store_unit_id": su.pk,
                    "trade_price": gb_data['product'].pre_sale_price,
                    "avg_price": gb_data['product'].pre_sale_price,
                    'trade_datetime': datetime.datetime.now(),
                })
                gb = GoodsBlock.objects.create(**gb_data)
                su.in_use = True
                su.save()
                # 入库节点
                gbc = GoodsBlockChain(
                    goods_block=gb,
                    operator_user_id=None,
                    chain_type=GoodsBlockChain.ChainType.IN_REPO.name,
                    node_datetime=datetime.datetime.now(),
                    storage_repo_id=su.repo.pk,
                    storage_repo_days=0
                )
                gbc_op = gbc.get_block_chain_node_outputs()
                gbc.title = gbc_op['title']
                gbc.contents = gbc_op['contents']
                gbc.repo_info = gbc_op['repo_info']
                gbc.save()
